package com.mqb.session;

import io.netty.channel.Channel;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class UserSession {
    private static ConcurrentHashMap<String, Channel> sessionMap = new ConcurrentHashMap<>();

    public static void add(String userId, Channel channel) {
        sessionMap.put(userId, channel);
    }

    public static void remove(String userId) {
        sessionMap.remove(userId);
    }

    public static Channel getChannelByUserId(String userId) {
        return sessionMap.get(userId);
    }

    public static String getUserIdByChannel(Channel channel) {
        Optional<Map.Entry<String, Channel>> first = sessionMap.entrySet().stream().filter(c -> c.getValue().equals(channel)).findFirst();
        Map.Entry<String, Channel> entry = first.orElse(null);
        return entry == null ? null : entry.getKey();
    }

    public static ConcurrentHashMap<String, Channel> getSessionMap() {
        return sessionMap;
    }
}
